import { Island } from '@hubspot/cms-components';
import {
  ModuleFields,
  TextField,
  BooleanField,
  ColorField,
  NumberField,
  FieldGroup,
} from '@hubspot/cms-components/fields';
// @ts-ignore
import QuoteCoverIsland from './islands/QuoteCoverIsland.tsx?island';

// ─── CSS ─────────────────────────────────────────────────────────────────────

const css = `
  .qc * { box-sizing: border-box; }
  .qc { font-family: system-ui, -apple-system, sans-serif; }

  .qc-wrap {
    border-radius: var(--qc-radius);
    overflow: hidden;
    box-shadow: 0 4px 32px rgba(0,0,0,0.08);
  }

  /* Hero */
  .qc-hero {
    background: var(--qc-gradient);
    padding: 52px 40px 44px;
    color: #fff;
    position: relative;
  }
  .qc-hero::before {
    content: '';
    position: absolute; inset: 0;
    background: radial-gradient(ellipse at 80% 10%, rgba(255,255,255,0.14), transparent 55%);
    pointer-events: none;
  }

  /* Status flag — anchored to the right edge of the hero */
  .qc-flag {
    position: absolute;
    top: 24px; right: 0;
    display: inline-flex; align-items: center; gap: 7px;
    padding: 8px 22px 8px 28px;
    font-size: 11px; font-weight: 700; letter-spacing: 0.5px; text-transform: uppercase;
    clip-path: polygon(18px 0%, 100% 0%, 100% 100%, 18px 100%, 0% 50%);
    box-shadow: -4px 2px 14px rgba(0,0,0,0.18);
    z-index: 1;
  }
  .qc-flag-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }

  .qc-prepared {
    font-size: 11px; font-weight: 700; letter-spacing: 2.5px;
    text-transform: uppercase; opacity: 0.65; margin: 0 0 10px;
  }
  .qc-buyer {
    font-size: 40px; font-weight: 900; margin: 0 0 8px;
    line-height: 1.1; text-shadow: 0 2px 14px rgba(0,0,0,0.18);
  }
  .qc-title { font-size: 17px; opacity: 0.78; margin: 0 0 36px; font-weight: 400; }

  /* Meta row: sender card + countdown side by side */
  .qc-meta { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
  .qc-meta-countdown { flex: 1; min-width: 180px; }

  /* Sender card */
  .qc-sender {
    background: rgba(255,255,255,0.15);
    backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
    border: 1px solid rgba(255,255,255,0.25);
    border-radius: 12px; padding: 12px 16px;
    display: flex; align-items: center; gap: 12px; color: #fff;
    flex-shrink: 0;
  }
  .qc-sender-avatar {
    width: 42px; height: 42px; border-radius: 50%;
    object-fit: cover; border: 2px solid rgba(255,255,255,0.5); flex-shrink: 0;
  }
  .qc-sender-avatar-fallback {
    width: 42px; height: 42px; border-radius: 50%;
    background: rgba(255,255,255,0.25); border: 2px solid rgba(255,255,255,0.4);
    display: flex; align-items: center; justify-content: center;
    font-size: 16px; font-weight: 800; color: #fff; flex-shrink: 0;
  }
  .qc-sender-name { font-weight: 700; font-size: 13px; line-height: 1.3; }
  .qc-sender-sub  { font-size: 11px; opacity: 0.72; margin-top: 1px; }

  /* Expired overlay */
  .qc-expired-banner {
    background: #fef2f2; border-top: 1px solid #fecaca;
    padding: 10px 32px; text-align: center;
    font-size: 13px; font-weight: 600; color: #991b1b;
  }
`;

// ─── Status flag ──────────────────────────────────────────────────────────────

const STATUS_MAP: Record<string, { dot: string; bg: string; color: string; label: string }> = {
  DRAFT:               { dot: '#94a3b8', bg: '#f1f5f9', color: '#475569', label: 'Draft' },
  PUBLISHED:           { dot: '#22c55e', bg: '#f0fdf4', color: '#166534', label: 'Published' },
  PENDING_SIGNATURE:   { dot: '#f59e0b', bg: '#fffbeb', color: '#92400e', label: 'Pending signature' },
  APPROVAL_NOT_NEEDED: { dot: '#22c55e', bg: '#f0fdf4', color: '#166534', label: 'Approved' },
  PENDING_APPROVAL:    { dot: '#f59e0b', bg: '#fffbeb', color: '#92400e', label: 'Pending approval' },
  REJECTED:            { dot: '#ef4444', bg: '#fef2f2', color: '#991b1b', label: 'Rejected' },
  CLOSED:              { dot: '#22c55e', bg: '#f0fdf4', color: '#166534', label: 'Accepted' },
};

function StatusFlag({ status }: { status: string | null }) {
  const s = (status && STATUS_MAP[status]) || { dot: '#94a3b8', bg: '#f1f5f9', color: '#475569', label: status || '—' };
  return (
    <div className="qc-flag" style={{ background: s.bg, color: s.color }}>
      <span className="qc-flag-dot" style={{ background: s.dot }} />
      {s.label}
    </div>
  );
}

// ─── Component ───────────────────────────────────────────────────────────────

export function Component({ fieldValues, hublData }: any) {
  const primary  = fieldValues?.styles?.primary?.color || hublData?.brandPrimary || '#6366f1';
  const accent   = fieldValues?.styles?.accent?.color  || '#8b5cf6';
  const radius   = fieldValues?.styles?.radius         ?? 16;
  const tagline  = fieldValues?.content?.tagline       || '';

  const showStatus    = String(fieldValues?.content?.showStatus)    !== 'false';
  const showSender    = String(fieldValues?.content?.showSender)    !== 'false';
  const showCountdown = String(fieldValues?.content?.showCountdown) !== 'false';

  const quoteTitle      = hublData?.quoteTitle      || null;
  const quoteStatus     = hublData?.quoteStatus     || null;
  const expirationDate  = hublData?.expirationDate  || null;
  const expired         = hublData?.expired         || false;
  const locale          = hublData?.locale          || 'en';
  const isPdf           = hublData?.isPdf           || false;
  const buyerCompany    = hublData?.buyerCompany    || null;
  const senderFirstName = hublData?.senderFirstName || null;
  const senderLastName  = hublData?.senderLastName  || null;
  const senderEmail     = hublData?.senderEmail     || null;
  const senderImageUrl  = hublData?.senderImageUrl  || null;
  const senderCompany   = hublData?.senderCompany   || null;

  const gradient = `linear-gradient(135deg, ${primary}, ${accent})`;

  const fmtDate = (ts: number) =>
    new Date(ts).toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' });

  const senderName    = [senderFirstName, senderLastName].filter(Boolean).join(' ');
  const senderInitial = senderFirstName?.[0] || senderLastName?.[0] || '?';

  const showCountdownEl = !isPdf && showCountdown && !!expirationDate;

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: css }} />
      <div
        id="qs-cover"
        className="qc"
        style={{
          maxWidth: 800,
          margin: '0 auto',
          paddingBottom: 24,
          ['--qc-primary' as any]: primary,
          ['--qc-accent' as any]:  accent,
          ['--qc-radius' as any]:  `${radius}px`,
          ['--qc-gradient' as any]: gradient,
        }}
      >
        <div className="qc-wrap">

          <div className="qc-hero">

            {/* Status flag — overlays top-right corner */}
            {showStatus && quoteStatus && <StatusFlag status={quoteStatus} />}

            {(tagline || buyerCompany) && (
              <p className="qc-prepared">{tagline || 'Prepared for'}</p>
            )}
            {buyerCompany && <h1 className="qc-buyer">{buyerCompany}</h1>}
            {quoteTitle   && <p className="qc-title">{quoteTitle}</p>}

            {/* Meta row: sender card + countdown filling remaining space */}
            {(showSender && senderName || showCountdownEl) && (
              <div className="qc-meta">
                {showSender && senderName && (
                  <div className="qc-sender">
                    {senderImageUrl
                      ? <img src={senderImageUrl} alt="" className="qc-sender-avatar" />
                      : <div className="qc-sender-avatar-fallback">{senderInitial}</div>
                    }
                    <div>
                      <div className="qc-sender-name">{senderName}</div>
                      {senderCompany && <div className="qc-sender-sub">{senderCompany}</div>}
                      {senderEmail   && <div className="qc-sender-sub">{senderEmail}</div>}
                    </div>
                  </div>
                )}

                {showCountdownEl && (
                  <div className="qc-meta-countdown">
                    <Island
                      module={QuoteCoverIsland}
                      expirationDate={expirationDate}
                      expired={expired}
                      primary={primary}
                      accent={accent}
                      hydrateOn="load"
                    />
                  </div>
                )}
              </div>
            )}

          </div>

          {expired && (
            <div className="qc-expired-banner">
              This quote expired on {expirationDate ? fmtDate(expirationDate) : '—'}. Please contact us for an updated offer.
            </div>
          )}

        </div>
      </div>
    </>
  );
}

// ─── Fields ──────────────────────────────────────────────────────────────────

export const fields = (
  <ModuleFields>
    <FieldGroup name="content" label="Content">
      <TextField
        name="tagline"
        label="Tagline (above buyer name)"
        default=""
        helpText="Leave blank to auto-show 'Prepared for' when buyer company is present"
      />
      <BooleanField name="showStatus"    label="Show quote status"       default={true} />
      <BooleanField name="showSender"    label="Show sender card"        default={true} />
      <BooleanField name="showCountdown" label="Show expiry countdown"   default={true} helpText="Web only — PDF always shows the static date in QuoteHeader" />
    </FieldGroup>
    <FieldGroup name="styles" label="Styles" tab="STYLE">
      <ColorField  name="primary" label="Primary colour"      default={{ color: '', opacity: 100 }} helpText="Leave blank to use brand colour" />
      <ColorField  name="accent"  label="Accent colour"       default={{ color: '#8b5cf6', opacity: 100 }} />
      <NumberField name="radius"  label="Border radius (px)"  default={16} />
    </FieldGroup>
  </ModuleFields>
);

// ─── Meta ─────────────────────────────────────────────────────────────────────

export const meta = {
  label: 'Quote Cover',
  content_types: ['QUOTE', 'QUOTE_BLUEPRINT'],
};

// ─── hublDataTemplate ────────────────────────────────────────────────────────

export const hublDataTemplate = `
  {% if quoteTemplateContext.buyerCompany %}
    {% set bc = quoteTemplateContext.buyerCompany %}
  {% endif %}

  {% set hublData = {
    "quoteTitle":      quoteTemplateContext.quote.hs_title,
    "quoteStatus":     quoteTemplateContext.quote.hs_quote_status,
    "expirationDate":  quoteTemplateContext.quote.hs_expiration_date,
    "expired":         quoteTemplateContext.quote.hs_expired,
    "locale":          quoteTemplateContext.quote.hs_locale,
    "isPdf":           true if quoteTemplateContext.quote.hs_pdf_generation_status == "PDF_GENERATING" else false,
    "buyerCompany":    bc.name,
    "senderFirstName": quoteTemplateContext.quote.hs_sender_firstname,
    "senderLastName":  quoteTemplateContext.quote.hs_sender_lastname,
    "senderEmail":     quoteTemplateContext.quote.hs_sender_email,
    "senderImageUrl":  quoteTemplateContext.quote.hs_sender_image_url,
    "senderCompany":   quoteTemplateContext.quote.hs_sender_company_name,
    "brandPrimary":    brand_settings.primaryColor.hex
  } %}
`;
